package com.fita.wechat.web.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import com.fita.wechat.web.interceptor.Mobile;
import com.fita.wechat.web.interceptor.Wechat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.fita.entity.agent.Agent;
import com.fita.entity.coupon.Coupon;
import com.fita.entity.coupon.CouponStatus;
import com.fita.wechat.entity.security.Login;
import com.fita.wechat.service.AgentService;
import com.fita.wechat.service.CouponService;
import com.fita.wechat.web.resolver.Secure;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("")
public class HomeController {
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
    @Autowired
    private CouponService couponService;
    
    @Autowired
    private AgentService agentService;
    
    /**
     * 
     * @return
     */
    @RequestMapping("")
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("redirect:/cars/search");
        return modelAndView;
    }
    

    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/coupon/{status}",method = RequestMethod.GET)
    @Mobile
    public ModelAndView coupon(@Secure Login login, @PathVariable String status ) {
    	ModelAndView modelAndView = new ModelAndView("profile/coupon-"+status);
    	
    	List<Coupon> allcoupons = couponService.listAllCoupons(login.getId());
    	//未使用的优惠券
        List<Coupon> unUseCoupons = new ArrayList<>();
        //已使用或者已过期的优惠券
        List<Coupon> usedCoupons = new ArrayList<>();
        

		for(Coupon coupon :allcoupons) {
			
			if (coupon.getStatus().equals(CouponStatus.USED) ||coupon.getStatus().equals(CouponStatus.OUT_OFF_DATE) ) {
				
				usedCoupons.add(coupon);
			}else if(coupon.getStatus().equals(CouponStatus.CLAIMED)) {
				
				unUseCoupons.add(coupon);
			}
		}
    	
    	if(status.equals("unuse")) {      		
    		
    		modelAndView.addObject("coupons",unUseCoupons);
    		
    	}else {
    		
    		modelAndView.addObject("coupons",usedCoupons);
    	}
    	
        return modelAndView;
    }

    @GetMapping("/redirect")
    public String redirect(@RequestParam String redirectUrl){

        return "redirect:" + redirectUrl;

    }
    

}
